package com.atcx.controller;

import com.atcx.pojo.SysUser;
import com.atcx.service.UserService;
import com.atcx.util.Constants;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * Copyright (C), 2017-2022, MIDOU
 * ClassName: UserController
 * Author:   pangshu
 * Date:     2022/7/21 15:20
 * Version: 1.0
 * Description:
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("login")
    public String login(SysUser user, HttpSession session){
        System.out.println(user.toString());
        SysUser userByNP = userService.getUserByNP(user);
        if (userByNP!=null){
            session.setAttribute(Constants.CURRENT_USER,userByNP.getUserId());
        }else {
            return "/index";
        }
        return "/manager";
    }
    @GetMapping("/exit")
    public String exit(HttpSession session){
        session.removeAttribute(Constants.CURRENT_USER);
        return "redirect:index.jsp";
    }
//    分页查询
    @GetMapping("/toList")
    public String toList(Model model,SysUser user, @RequestParam(required = true,defaultValue = "1") Integer currentPage, @RequestParam(required = true,defaultValue = "5") Integer pageSize){
     PageInfo<SysUser> pageInfo = userService.queryUserByPage(user,currentPage,pageSize);
     model.addAttribute("user",user);
     model.addAttribute("page",pageInfo);
     model.addAttribute("one","afagdhf");
     return "list";
    }
    @GetMapping("edit")
    public String toEdit(Model model,@RequestParam(required = true,defaultValue = "0") Integer id){
        if (id!=0){
            SysUser user = userService.getUserById(id);
            model.addAttribute("user",user);
        }
        return "edit";
    }
//    保存和修改信息
    @PostMapping("save")
    public String save(Model model,SysUser  user){
       Boolean flag =  userService.saveUser(user);
       if (flag){
           PageInfo<SysUser> pageInfo = userService.queryUserByPage(user,1,5);
           model.addAttribute("user",user);
           model.addAttribute("page",pageInfo);
       }
        return "list";
    }
    @GetMapping("deleteById")
    public String  deleteById(Integer id){
        Boolean flag =userService.deleteById(id);
        return "list";
    }
}
